package cmd

import (
	"APT/internal/gateway"
	"APT/internal/library/casbin"
	"APT/internal/middleware"
	"APT/internal/service"
	"APT/router"
	"APT/utility/opentelemetry"
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
)

var (
	Main = &gcmd.Command{
		Description: `默认启动Http服务`,
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			return Http.Func(ctx, parser)
		},
	}

	Http = &gcmd.Command{
		Name:  "Http",
		Usage: "start",
		Brief: "start http server",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			// 初始化OpenTelemetry
			shutdown := opentelemetry.InitOpenTelemetry()
			defer shutdown()
			// 修改sql日志输出文件
			g.DB().SetLogger(g.Log())
			// 启动服务监控
			service.BasicsAdminMonitor().StartMonitor(ctx)

			// 初始化功能库配置
			service.BasicsConfig().InitConfig(ctx)

			// 加载超管数据
			service.BasicsAdminMember().LoadSuperAdmin(ctx)

			// 初始化casbin权限
			casbin.InitEnforcer(ctx)

			s := g.Server()
			// 注册全局中间件
			s.BindMiddleware("/*any", []ghttp.HandlerFunc{
				middleware.Ctx,
				middleware.CORS,
				middleware.Blacklist,
				middleware.HandleResponse,
			}...)

			s.Group("/", func(group *ghttp.RouterGroup) {
				// 注册后台路由
				router.Admin(ctx, group)
				// 注册Api路由
				router.Notify(ctx, group)
				// 注册App路由
				router.App(ctx, group)
				// 注册websocket路由
				router.WebSocket(ctx, group)
			})
			s.Run()
			return nil
		},
	}

	AppGateway = &gcmd.Command{
		Name:  "AppGateway",
		Usage: "start",
		Brief: "APP加密网关",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			gateway.AppGateway()
			return
		},
	}
)

func init() {
	if err := Main.AddCommand(
		Http,
		AppGateway,
		MQ,
		MQOrderStay,
		MQExp,
		MQOrderExpire,
		MQPlaceOrder,
		MQAvailabilities,
		MQRebate,
		CronAvailabilities,
		CronProperties,
		CronFeeds,
		CronRoomTypeAndRates,
		CronFoodSettlement,
		CronCarSettlement,
		CronSpaSettlement,
		CronCouponExp,
	); err != nil {
		panic(err)
	}
}
